package com.kingdee.pda.ui.check_order

import android.app.Activity
import android.app.Service
import android.content.Context
import android.content.Intent
import android.os.Bundle
import android.os.Handler
import android.os.Message
import android.os.Vibrator
import android.text.TextUtils
import android.util.AttributeSet
import android.util.Log
import android.view.KeyEvent
import android.view.View
import android.view.WindowManager
import android.view.inputmethod.InputMethodManager
import android.widget.*
import com.example.basecommon.utils.MusicUtils
import com.example.basecommon.utils.PreferencesUtils
import com.kingdee.pda.R
import com.kingdee.pda.entity.*
import com.kingdee.pda.entity.CheckOrderDetailBean.Detailinfo
import com.kingdee.pda.entity.OrderSubmitBean.Invdetail
import com.kingdee.pda.plugins.http.common.OnRequestCallback
import com.kingdee.pda.plugins.http.serverinterface.impl.QueryGoodsImpl
import com.kingdee.pda.ui.activity.BaseTitleActivity
import com.kingdee.pda.ui.check_order.CheckOrderDetailActivity
import com.kingdee.pda.ui.check_order.CheckOrderUtil.transferDetailsOrg
import com.kingdee.pda.ui.check_order.DetailContract.IDetailView
import com.kingdee.pda.ui.dialog.RemindDialog
import com.kingdee.pda.ui.dialog.RemindDialog.OnConfirmClickListener
import com.kingdee.pda.ui.popupwindow.ListSelectorPpWindow
import com.kingdee.pda.ui.widget.CleanableEditText
import com.kingdee.pda.util.ConstantPreference
import com.kingdee.pda.util.StringUtils
import com.kingdee.pda.util.ToastUtils
import org.json.JSONObject
import java.util.*


class CheckOrderDetailActivity : BaseTitleActivity(), View.OnKeyListener, IDetailView,
    View.OnClickListener {
    private  final var et_warehouse_code: CleanableEditText? =null
    private var et_order_count: CleanableEditText? = null
    private var et_item_bar_code: CleanableEditText? = null
    private var et_owner: CleanableEditText? = null
    private var et_ower_type: CleanableEditText? = null
    private var et_warehouse_status: CleanableEditText? = null
    var locationList: MutableList<Detailinfo.Location> = ArrayList()
    private var curWarehouseIndex = 0
    private var curSkuCount = 0
    var iv_owner_type_select: ImageView? = null
    var iv_order_owner_select: ImageView? = null
    var iv_et_warehouse_status_select: ImageView? = null
    var btn_next_warehouse: Button? = null
    var btn_back: Button? = null
    var btn_finish: Button? = null
    var tv_warehouse_num: TextView? = null
    var tv_sku_num: TextView? = null
    var tv_rec_warehourse: TextView? = null
    var list_view: ListView? = null
    private var presenter: OrderDetailPresenter? = null
    var mOperateConfirmDialog: RemindDialog? = null

    // submit result
    private val submitBean = OrderSubmitBean()
    private val submitList: MutableList<Invdetail> = ArrayList()
    private lateinit var adapter: SubmitOrderListAdapter
    private var bilStatus // 3 待初盘 5 待复盘
            : String? = null
    var location: Detailinfo.Location? = null

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
    }

    override fun onActivityCreate(savedInstanceState: Bundle?) {
        super.onActivityCreate(savedInstanceState)
        setContentView(R.layout.activity_check_order_detail)
        presenter = OrderDetailPresenter(this, this)
        val i = intent
        if (i != null) {
            val bilNumber = i.getStringExtra("bilno")
            bilStatus = i.getStringExtra("bilstatus")
            presenter!!.getOrderDetail(bilNumber, bilStatus)
            presenter!!.getAllInvStatus()
            submitBean.inventorynumber = bilNumber
        }
    }

    override fun onCreateView(name: String?, context: Context?, attrs: AttributeSet?): View? {
        return super.onCreateView(name, context, attrs)
    }

    override fun changeWarehouse(warehouse: Warehouse) {}
    override fun getDetailSuccess(orderDetailBean: CheckOrderDetailBean) {
        updateOrderView(orderDetailBean)
    }

    override fun getDetailFail(msg: String) {
        ToastUtils.showShort(this, msg)
    }

    override fun initView() {
        super.initView()
        setTitle("库存盘点")
        et_order_count = findViewById(R.id.et_order_count)
        et_order_count?.setOnKeyListener(this);
        if (PreferencesUtils.getInt(CheckOrderListActivity.CHECK_ORDER_TYPE_KEY) == 1) {
            et_order_count!!.setText("1")
            et_order_count!!.setEnabled(false)
            et_order_count!!.setClearDrawableVisible(false)
        } else {
            et_order_count!!.setFocusable(true)
        }
        et_warehouse_code = findViewById(R.id.et_warehouse_code)
        setEditTextScannerEvents(et_warehouse_code, this)
        et_warehouse_code!!.requestFocus();

        /***
         * 获取焦点但是隐藏键盘
         * **/

//        et_warehouse_code!!.setFocusableInTouchMode(true);//禁止弹出
//        et_warehouse_code!!.requestFocus();//获取焦点
//        getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);

//         var imm:InputMethodManager =
//             getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager;
//        imm.toggleSoftInput(0, InputMethodManager.HIDE_NOT_ALWAYS);
        et_item_bar_code = findViewById(R.id.et_item_bar_code)
        setEditTextScannerEvents(et_item_bar_code, this)
        et_ower_type = findViewById(R.id.et_ower_type)
        et_owner = findViewById(R.id.et_owner)
        et_warehouse_status = findViewById(R.id.et_warehouse_status)
        iv_owner_type_select = findViewById(R.id.iv_owner_type_select)
        iv_owner_type_select!!.setOnClickListener(this)
        iv_order_owner_select = findViewById(R.id.iv_order_owner_select)
        iv_order_owner_select!!.setOnClickListener(this)
        iv_et_warehouse_status_select = findViewById(R.id.iv_et_warehouse_status_select)
        iv_et_warehouse_status_select!!.setOnClickListener(this)
        tv_sku_num = findViewById(R.id.tv_sku_num)
        btn_next_warehouse = findViewById(R.id.btn_next_warehouse)
        btn_next_warehouse!!.setOnClickListener(View.OnClickListener { v: View? -> nextWarHouse() })
        findViewById<View>(R.id.btn_back).setOnClickListener { v: View? -> onBackPressed() }
        findViewById<View>(R.id.iv_back).setOnClickListener(null);
        findViewById<View>(R.id.iv_back).setOnClickListener { v: View? -> onBackPressed() }
        btn_finish = findViewById(R.id.btn_finish)
        btn_finish!!.setOnClickListener(View.OnClickListener { v: View? -> submitOrder() })
        list_view = findViewById(R.id.list_view)
        tv_rec_warehourse = findViewById(R.id.tv_rec_warehourse)
        tv_warehouse_num = findViewById(R.id.tv_warehouse_num)
        adapter = SubmitOrderListAdapter(this)
        list_view!!.setAdapter(adapter)
    }

    override fun initData() {
        super.initData()
    }

    var onEnterTime: Long = 0;

    override fun onKey(v: View, keyCode: Int, event: KeyEvent): Boolean {
        if (v !is EditText) {
            return false
        }
        val input = v.text.toString().trim { it <= ' ' }
        if ((keyCode == KeyEvent.KEYCODE_SYSRQ || keyCode == KeyEvent.KEYCODE_ENTER) && event.action == KeyEvent.ACTION_UP) {
            val invdetail = Invdetail()
            if (v.getId() == R.id.et_warehouse_code) {
                // 库位编码
                val res = isWarehouseInBil(input)
                if (res) {
                    et_item_bar_code!!.isFocusable = true
                    et_item_bar_code!!.requestFocus()
                    et_item_bar_code!!.isFocusableInTouchMode = true
                    invdetail.locationid = input
                } else {
                    ToastUtils.showShort(this@CheckOrderDetailActivity, "库位编码不存在于该盘点单")
                }
                return true
            } else if (v.getId() == R.id.et_item_bar_code) {
                // 防止连续触发
                if (System.currentTimeMillis() - onEnterTime < 1000) {
                    return true
                }
                onEnterTime = System.currentTimeMillis()

                if (et_item_bar_code?.text.toString().length < 3) {
                    ToastUtils.showShort(this@CheckOrderDetailActivity, "商品条码长度不能少于3")
                    return true
                }
                // TODO 商品条码，两个逻辑，配置开关是否开启
                val res = isItemBarInBil(et_warehouse_code?.text.toString(), input, invdetail)
                if (res || PreferencesUtils.getBoolean(
                        this@CheckOrderDetailActivity,
                        ConstantPreference.INVLIBOUT
                    )
                ) {
                    btn_finish!!.isEnabled = true
                    handleSkuItemScan(et_warehouse_code?.text.toString(), input, invdetail)
                } else {
                    ToastUtils.showShort(this@CheckOrderDetailActivity, "商品条码不存在于该盘点单")
                }
                return true
            } else if (v.getId() == R.id.et_order_count) {
                if (!TextUtils.isEmpty(input) && currentCheckSku != null) {
                    insertSubmitData(invdetail, currentCheckSku!!)
                    et_item_bar_code?.requestFocus()
                }
                return true
            }
        }
        return false
    }

    override fun getScanResult(scanResult: String) {
        super.getScanResult(scanResult)
        Log.d("imesong", "getScanResult == $scanResult")
    }

    override fun onClick(v: View) {
        super.onClick(v)
        when (v.id) {
            R.id.iv_owner_type_select -> showOwnerTypePopup()
            R.id.iv_order_owner_select -> showOwnerPopup()
            R.id.iv_et_warehouse_status_select -> showInvStatusPop()
            else -> {}
        }
    }

    override fun onResume() {
        super.onResume()
    }

    /**
     * 查询货主
     *
     * @param list
     */
    override fun getProductOwnerSuccess(list: List<ProductOwnerBean>) {
// update ui
        val details = Detailinfo()
        details.detailowner = Detailinfo.Detailowner()
        details.detailowner!!.name = Detailinfo.Detailowner.Name()
        details.invstatus = Detailinfo.Invstatus()
        details.invstatus!!.name = Detailinfo.Invstatus.Name()
        details.location = Detailinfo.Location()
        details.sku = Detailinfo.Sku()
        details.sku!!.itembarcode = Detailinfo.Sku.Itembarcode()

        details.detailownertypename = list.get(0).ownertypename
        details.detailowner!!.name!!.zhCn = list.get(0).ownername
        details.invstatus!!.name!!.zhCn = "可用"
        details.location!!.number = et_warehouse_code?.text.toString()
        details.detailowner!!.id = list.get(0).owner

        details.sku!!.id = list.get(0).sku
        details.detailownertype = list.get(0).ownertype
        details.sku!!.itembarcode!!.number = et_item_bar_code?.text.toString()
        details.sku?.itemskucode = list.get(0).skucode

        details.location!!.id = location?.id!!
        details.invstatus!!.id = list.get(0).invstatus


        if (details.detailownertypename != null) {
            et_ower_type!!.setText(details.detailownertypename)
        }
        et_owner!!.setText(details?.detailowner?.name?.zhCn)
        et_warehouse_status!!.setText(details?.invstatus?.name?.zhCn)

        if (PreferencesUtils.getInt(
                this@CheckOrderDetailActivity,
                CheckOrderListActivity.CHECK_ORDER_TYPE_KEY
            ) == 1
        ) {
            insertSubmitData(Invdetail(), details);
            et_item_bar_code?.selectAll();
            val inputMethodManager: InputMethodManager =
                getSystemService(INPUT_METHOD_SERVICE) as InputMethodManager
            inputMethodManager.hideSoftInputFromWindow(
                et_item_bar_code?.getWindowToken(),
                InputMethodManager.HIDE_NOT_ALWAYS
            )
        } else {
            currentCheckSku = details;
            et_order_count?.requestFocus();
        }
    }

    override fun getProductFail(msg: String) {
        MusicUtils.getInstance().playSuccess(3)
        ToastUtils.showShort(this@CheckOrderDetailActivity, msg)
    }

    private fun updateOrderView(bean: CheckOrderDetailBean) {
        et_warehouse_code!!.setClearDrawableVisible(false)
        tv_warehouse_num!!.text = bean.billno
        if (bean.detailinfos != null) {
            curDetailList.clear()
            transferDetailsOrg(bean.detailinfos!!)
            curDetailList.addAll(bean.detailinfos!!)
        }
        // 推荐库位
        tv_rec_warehourse!!.text = getRecWareLocation(curDetailList, bilStatus)
    }

    //TODO  下一个库位
    private fun nextWarHouse() {
        if (curWarehouseIndex + 1 < locationList.size) {
            val location = locationList[curWarehouseIndex + 1]
            curWarehouseIndex++
            tv_rec_warehourse!!.text = location.number
            resetEtStatus()
        }
    }

    private var currentCheckSku: Detailinfo? = null;

    // scan sku code
    private fun handleSkuItemScan(warehouseId: String, itemBarCode: String, invdetail: Invdetail) {

        var details = getDetailinfo(itemBarCode, warehouseId)
        if (details != null) {
//            presenter!!.getProductOwner(
//                    details.sku?.itembarcode?.number.toString(),
//                    et_warehouse_code!!.text.toString(),
//                    details.invstatus?.id.toString() + "",
//                PreferencesUtils.getBoolean(this@CheckOrderDetailActivity, ConstantPreference.INVLIBOUT)
//            )
            // update ui
            if (details.detailownertypename != null) {
                et_ower_type!!.setText(details.detailownertypename)
            }
            et_owner!!.setText(details?.detailowner?.name?.zhCn)
            et_warehouse_status!!.setText(details?.invstatus?.name?.zhCn)

            if (PreferencesUtils.getInt(
                    this@CheckOrderDetailActivity,
                    CheckOrderListActivity.CHECK_ORDER_TYPE_KEY
                ) == 1
            ) {
                insertSubmitData(invdetail, details);
                et_item_bar_code?.selectAll();
                val inputMethodManager: InputMethodManager =
                    getSystemService(INPUT_METHOD_SERVICE) as InputMethodManager
                inputMethodManager.hideSoftInputFromWindow(
                    et_item_bar_code?.getWindowToken(),
                    InputMethodManager.HIDE_NOT_ALWAYS
                )
            } else {
                currentCheckSku = details;
                et_order_count?.requestFocus();
            }
        } else if (PreferencesUtils.getBoolean(
                this@CheckOrderDetailActivity,
                ConstantPreference.INVLIBOUT
            )
        ) {
            //TODO 扫描盘点单以外的商品
            presenter!!.getProductOwner(
                itemBarCode,
                "",
                "",
                true
            )
        }
    }

    // 插入提交数据
    private fun insertSubmitData(invdetail: Invdetail, details: Detailinfo) {
        var isExists = false
        for (i in submitList.indices) {
            if (submitList[i].warehouseid == details.location?.number && submitList[i].skuid == details.sku?.id.toString()) {
                isExists = true
                if (PreferencesUtils.getInt(
                        this@CheckOrderDetailActivity,
                        CheckOrderListActivity.CHECK_ORDER_TYPE_KEY
                    ) == 1
                ) {
                    submitList[i].invnumber =
                        (submitList[i].invnumber!!.toInt() + et_order_count!!.text.toString()
                            .toInt()).toString()
                } else {
                    if (submitList[i].ownerid == details.detailowner?.id.toString() && submitList[i].invstatus == details.invstatus?.name?.zhCn.toString()) {
                        submitList[i].invnumber =
                            (submitList[i].invnumber!!.toInt() + et_order_count!!.text.toString()
                                .toInt()).toString()
                    }
                }
            }
        }
        if (!isExists) {
            invdetail.warehouseid = details.location?.number
            invdetail.skuid = details.sku?.id?.toString() + ""
            invdetail.skuCode = details.sku?.itemskucode
            invdetail.ownertype = details.detailownertype
            invdetail.ownerid = details.detailowner?.id?.toString() + ""
            invdetail.owner = details.detailowner?.name?.zhCn
            invdetail.invstatus = details.invstatus?.name?.zhCn
            invdetail.itembarcode = details.sku?.itembarcode?.number + ""
            if (invdetail.invnumber == null) {
                invdetail.invnumber = "0"
            }
            if (StringUtils.isNumeric(invdetail.invnumber) && StringUtils.isNumeric(
                    et_order_count!!.text.toString()
                )
            ) {
                var orderCount = 0;
                if (et_order_count!!.text.toString() != "") {
                    orderCount = et_order_count!!.text.toString().toInt();
                }
                invdetail.invnumber =
                    (invdetail!!.invnumber!!.toInt() + orderCount).toString() + ""
            }
            invdetail.locationid = details.location?.id.toString() + ""
            invdetail.invstatusid = details.invstatus?.id.toString() + ""
            submitList.add(invdetail)
        }

        btn_finish!!.isEnabled = submitList != null && submitList.size > 0
        with(submitBean.invdetails) {
            this.clear()
            this.addAll(submitList)
        }
        curSkuCount = 0;
        for (i in submitList.indices) {
            curSkuCount += submitList[i].invnumber!!.toInt()
        }
        tv_sku_num!!.text = "" + curSkuCount
        // 重新计算盘点数量
        adapter.data = submitList
        currentCheckSku = null;
    }

    //TODO 提交
    private fun submitOrder() {
        Log.d("submit", submitBean.toString())

        if (mOperateConfirmDialog == null) {
            mOperateConfirmDialog = RemindDialog(this@CheckOrderDetailActivity)
        }
        mOperateConfirmDialog?.setTitle("确认")
        mOperateConfirmDialog?.setContent("确定提交盘库？")
        mOperateConfirmDialog?.setShowCancelButton()
        mOperateConfirmDialog?.setListener(OnConfirmClickListener {
            presenter!!.commitOrder(
                submitBean
            )
        })
        mOperateConfirmDialog?.show()

    }

    override fun commitOrderSuccess(msg: String) {
        ToastUtils.showShort(this, msg)
        submitList.clear()
        resetEtStatus()
        adapter.data = submitList
    }

    override fun commitOrderFail(msg: String) {
        ToastUtils.showShort(this, "commitOrderFail $msg")
    }

    override fun getInvstatusSuccess(list: List<InvstatusBean>) {
        if (list != null && list.size > 0) {
            Log.d("getInvstatusSuccess", "list.size" + list.size)
            allInvstatus.clear()
            allInvstatus.addAll(list)
        }
    }

    /**
     * 展示货主类型弹框
     */
    private fun showOwnerTypePopup() {
        val ownTypeSet: MutableSet<String> = HashSet()
        for (i in curDetailList.indices) {
            curDetailList[i].detailownertypename?.let { ownTypeSet.add(it) }
        }
        val ownTypeList: List<String> = ArrayList(ownTypeSet)
        val locationSelector = ListSelectorPpWindow(
            this@CheckOrderDetailActivity,
            R.drawable.shape_bg_edit_selected,
            et_ower_type!!.width,
            ownTypeList
        ) { item ->
            val ownType = item as String
            et_ower_type!!.setText(ownType)
        }
        locationSelector.showAsDropDown(et_ower_type, 0, 10)
    }

    /**
     * 货主 popup
     */
    private fun showOwnerPopup() {
        val ownSet: HashSet<String> = object : HashSet<String>() {}
        for (i in curDetailList.indices) {
            curDetailList[i].detailowner?.name?.zhCn?.let { ownSet.add(it) }
        }
        val locationSelector = ListSelectorPpWindow(
            this@CheckOrderDetailActivity,
            R.drawable.shape_bg_edit_selected,
            et_owner!!.width,
            ownSet.toList()
        ) { item ->
            val owner = item as? String
            et_owner!!.setText(owner)
        }
        locationSelector.showAsDropDown(et_owner, 0, 10)
    }

    /**
     * 库存状态 popup
     */
    private fun showInvStatusPop() {
        val locationSelector = ListSelectorPpWindow(
            this@CheckOrderDetailActivity,
            R.drawable.shape_bg_edit_selected,
            et_warehouse_status!!.width,
            allInvstatus
        ) { item ->
            val invstatus = item as InvstatusBean
            et_warehouse_status!!.setText(invstatus.name)
        }
        locationSelector.showAsDropDown(et_warehouse_status, 0, 10)
    }

    override fun getInvstatusFail(msg: String) {
        ToastUtils.showShort(this@CheckOrderDetailActivity, msg)
    }


    var mHandler: Handler = object : Handler() {
        override fun handleMessage(msg: Message?) {
            super.handleMessage(msg)
            isExit = false
        }
    }

    private var isExit: Boolean = false;
    override fun onBackPressed() {
        if (!isExit) {
            isExit = true;
            Vibrate(this@CheckOrderDetailActivity,500)
            ToastUtils.showShort(this@CheckOrderDetailActivity, "数据未保存，请确认")
            // 利用handler延迟发送更改状态信息
            mHandler.sendEmptyMessageDelayed(0, 2000);
        } else {
            finish();
        }
    }


    fun Vibrate(act: Activity, ms: Long) {
        val vib: Vibrator = act.getSystemService(Service.VIBRATOR_SERVICE) as Vibrator
        vib.vibrate(ms)
    }
    /**
     * 获取推荐库位
     */
    private fun getRecWareLocation(list: List<Detailinfo>?, bilStatus: String?): String? {
        if (list != null && list.size > 0) {
            locationList.clear()
        }
        for (i in list!!.indices) {
            //TODO 区分盘点状态， 3 、5
//            if (bilStatus == "5") {
//                if (list.get(i).sku.status == bilStatus) {
//                    locationList.add(list.get(i).location);
//                }
//            }
            list[i].location?.let { locationList.add(it) }
        }
        locationList.sortWith(Comparator { o1: Detailinfo.Location, o2: Detailinfo.Location -> (o1.id - o2.id).toInt() })
        curWarehouseIndex = 0
        return locationList[0].number
    }

    // 库位校验
    private fun isWarehouseInBil(warehouseId: String): Boolean {
        if (TextUtils.isEmpty(warehouseId)) return false
        for (i in locationList.indices) {
            if (TextUtils.equals(
                    locationList[i].number?.lowercase(Locale.getDefault()), warehouseId.lowercase(
                        Locale.getDefault()
                    )
                )
            ) {
                location = locationList[i]
                return true
            }
        }
        return false
    }

    // 商品码校验
    private fun isItemBarInBil(
        warehouseId: String,
        itemBarCode: String,
        invdetail: Invdetail
    ): Boolean {
        if (TextUtils.isEmpty(itemBarCode)) return false
        var detailinfo = getDetailinfo(itemBarCode, warehouseId)
        if (detailinfo != null) {
            invdetail.skuid = detailinfo.sku?.skuid.toString() + ""
            invdetail.itembarcode = detailinfo.sku?.itembarcode?.number
            // 货主类型
            et_ower_type!!.setText(detailinfo.detailownertypename)
            return true
        }
        return false
    }

    private fun getDetailinfo(itemBarCode: String, warehouseId: String): Detailinfo? {
        for (i in curDetailList.indices) {
            val detailinfo = curDetailList[i]
            if (TextUtils.equals(
                    detailinfo.sku?.itembarcode?.number,
                    itemBarCode
                ) && TextUtils.equals(
                    detailinfo.location?.number?.lowercase(Locale.getDefault()),
                    warehouseId.lowercase(Locale.getDefault())
                )
            ) {
                return detailinfo
            } else {
                // 查找辅助条码
                for (i2 in detailinfo.sku?.itembarcode?.entryentity?.indices!!) {
                    val entryentity = detailinfo.sku?.itembarcode?.entryentity!![i2]
                    if (TextUtils.equals(entryentity.itemnumber, itemBarCode) && TextUtils.equals(
                            detailinfo.location?.number?.lowercase(Locale.getDefault()),
                            warehouseId.lowercase(Locale.getDefault())
                        )
                    ) {
                        return detailinfo
                    }
                }
            }
        }
        return null
    }

    private fun resetEtStatus() {
        et_warehouse_code!!.requestFocus()
        et_warehouse_status!!.setText("")
        et_item_bar_code!!.setText("")
        et_ower_type!!.setText("")
        et_owner!!.setText("")
        et_warehouse_status!!.setText("")
        // 库位已盘点sku 数
        tv_sku_num!!.text = ""
        curSkuCount = 0
    }

    companion object {
        // 库存状态
        private val allInvstatus: MutableList<InvstatusBean> = ArrayList()
        private val curDetailList: MutableList<Detailinfo> = ArrayList()
        fun startAction(context: Context) {
            context.startActivity(Intent(context, CheckOrderDetailActivity::class.java))
        }
    }
}